package com.atguigu.tingshu.user.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.hash.Hash;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.service.KafkaService;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.common.util.MongoUtil;
import com.atguigu.tingshu.model.user.UserListenProcess;
import com.atguigu.tingshu.user.service.UserListenProcessService;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.atguigu.tingshu.vo.user.UserListenProcessVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@SuppressWarnings({"all"})
public class UserListenProcessServiceImpl implements UserListenProcessService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 获取当前用户对某个声音播放进度
     *
     * @param userId
     * @param trackId
     * @return
     */
    @Override
    public BigDecimal getTrackBreakSecond(Long userId, Long trackId) {
        //1.创建查询条件
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId).and("trackId").is(trackId));
        //2.获取播放进度
        UserListenProcess userListenProcess = mongoTemplate.findOne(query, UserListenProcess.class, MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId));
        if (userListenProcess != null) {
            return userListenProcess.getBreakSecond();
        }
        return new BigDecimal("0.00");
    }

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private KafkaService kafkaService;

    /**
     * 更新声音播放进度
     *
     * @param userId
     * @param userListenProcessVo
     */
    @Override
    public void updateListenProcess(Long userId, UserListenProcessVo userListenProcessVo) {
        //1.根据用户ID+声音ID查询播放进度
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId).and("trackId").is(userListenProcessVo.getTrackId()));
        //2.获取播放进度
        UserListenProcess userListenProcess = mongoTemplate.findOne(query, UserListenProcess.class, MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId));
        //2.如播放进度记录存在-更新播放进度
        if (userListenProcess != null) {
            userListenProcess.setBreakSecond(userListenProcessVo.getBreakSecond());
            userListenProcess.setUpdateTime(new Date());
        } else {
            //3.如播放进度记录不存在-新增播放进度
            userListenProcess = new UserListenProcess();
            userListenProcess.setUserId(userId);
            userListenProcess.setTrackId(userListenProcessVo.getTrackId());
            userListenProcess.setAlbumId(userListenProcessVo.getAlbumId());
            userListenProcess.setBreakSecond(userListenProcessVo.getBreakSecond());
            userListenProcess.setCreateTime(new Date());
            userListenProcess.setUpdateTime(new Date());
        }
        mongoTemplate.save(userListenProcess, MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId));
        //4.发送MQ消息到Kafka通知专辑服务，更新 声音/专辑 播放量累加
        //4.1 同一用户同一声音当天只能累加一次播放量 set EX(过期时间单位秒) NX（当Key不存在才能存入成功）
        String key = "user:process:" + userId + ":" + userListenProcessVo.getTrackId();
        long time = DateUtil.endOfDay(new Date()).getTime();
        long ttl = time - System.currentTimeMillis();
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(key, "", ttl, TimeUnit.MILLISECONDS);
        if (flag) {
            //当天第一次更新播放统计信息
            //4.2 封装更新统计数值对象
            TrackStatMqVo mqVo = new TrackStatMqVo();
            mqVo.setAlbumId(userListenProcessVo.getAlbumId());
            mqVo.setTrackId(userListenProcessVo.getTrackId());
            mqVo.setStatType(SystemConstant.TRACK_STAT_PLAY);
            mqVo.setCount(1);
            mqVo.setBusinessNo(RedisConstant.BUSINESS_PREFIX + IdUtil.fastSimpleUUID());
            //4.3 发送消息到更新声音统计话题中
            kafkaService.sendKafkaMessage(KafkaConstant.QUEUE_TRACK_STAT_UPDATE, JSON.toJSONString(mqVo));
        }
    }

    /**
     * 获取当前用户最近播放专辑及声音ID
     *
     * @return
     */
    @Override
    public Map<String, Long> getLatelyTrack() {
        //1.获取当前用户ID
        Long userId = AuthContextHolder.getUserId();
        //2.根据用户ID+更新时间倒序获取最近一条播放进度
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        query.with(Sort.by(Sort.Direction.DESC, "updateTime"));
        query.limit(1);
        UserListenProcess listenProcess = mongoTemplate.findOne(query, UserListenProcess.class, MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId));
        if (listenProcess != null) {
            //3.从播放进度中获取专辑ID，声音ID
            Map<String, Long> map = new HashMap<>();
            map.put("albumId", listenProcess.getAlbumId());
            map.put("trackId", listenProcess.getTrackId());
            return map;
        }
        return null;
    }

}
